/**
 * 
 */
package com.taoban.shopdata.thread;

import java.io.IOException;

import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathExpressionException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.taoban.shopdata.core.impl.YHDShopDataConsumer;
import com.yufei.utils.CommonUtil;
import com.yufei.utils.DateUtil;
import com.yufei.utils.ExceptionUtil;
import com.yufei.utils.IOUtils;
import com.yufei.utils.PatternUtils;
import com.yufei.utils.XPathUtil;

/**
 * @author jasstion
 * 上午10:01:12
 * 用户定期的访问并保存整个一号店的产品信息（比如:itemId（区别与productId）,以及价格）
 */
public class YHDProductCollectThread implements Runnable {
	private static Log mLog = LogFactory.getLog(YHDProductCollectThread.class);

	/* (non-Javadoc)
	 * @see java.lang.Runnable#run()
	 */
	@Override
	public void run() {
		// TODO Auto-generated method 
		mLog.info("开始更行一号店商品信息库，时间为:"+DateUtil.getCurrentDateString()+"");
		YHDShopDataConsumer.productPriceMap.clear();
		List<String>  productIds=null;
		String configXml=IOUtils.translantByteStreamToString(IOUtils.translantStreamToByte(Thread.currentThread().getContextClassLoader().getResourceAsStream("config.xml")), "utf-8");
		String urlIndex=null;
		String productPre=null;
			try {
				 urlIndex=XPathUtil.getNodeTextByXPath(configXml, "//yihaodian/urlIndex");
				 if(CommonUtil.isEmptyOrNull(urlIndex)){
					 mLog.info("解析配置文件获取一号店的urlIndex错误！");
					 return ;
					
				 }
				 productPre=XPathUtil.getNodeTextByXPath(configXml, "//yihaodian/productUrlPre");
				 productIds=XPathUtil.getNodeListTextByXPath(CommonUtil.getHtmlContent(urlIndex, false), "//products/product");
                 for(String productId:productIds){
                	 setProductPrice(productPre+productId);
                	 mLog.info("开始解析产品url："+productPre+productId+"");
                 }
                 mLog.info("此次共导入一号店商品个数:"+YHDShopDataConsumer.productPriceMap.size()+"");
         		 mLog.info("全部更行一号店商品信息库结束，时间为:"+DateUtil.getCurrentDateString()+"");

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
 
			
			
		

	}


	private void setProductPrice(String productUrl){
		try {
			String productsInfo=CommonUtil.getHtmlContent(productUrl, false);
			NodeList productNodes=XPathUtil.getNodeListtByXPath(productsInfo, "//product");
			Node productNode=null;
			String itemId=null;
			String price=null;
			String temp=null;
			for(int i=0;i<productNodes.getLength();i++){
				productNode=productNodes.item(i);
				temp=XPathUtil.getValueOfNode(productNode, "product_url");
				itemId=PatternUtils.getStrByRegex(temp, "item/(.*)");
				
				price=XPathUtil.getValueOfNode(productNode, "sale_price");
				price=PatternUtils.getStrByRegex(price, "\n(.*?)\n");
				if(CommonUtil.isEmptyOrNull(itemId)||CommonUtil.isEmptyOrNull(price)){
					continue;
				}
				mLog.info("商品"+itemId+"最新价格为："+price+"");
				YHDShopDataConsumer.productPriceMap.put(itemId, Double.parseDouble(price));
				
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			mLog.info("访问"+productUrl+"并提取里面的产品信息出错！详细错误信息是:"+ExceptionUtil.getExceptionDetailsMessage(e)+"");
		}
		
		
	}
public static void main(String[] args) throws XPathExpressionException, ParserConfigurationException, SAXException, IOException{
	String productsInfo=IOUtils.translantByteStreamToString(IOUtils.translantStreamToByte(Thread.currentThread().getContextClassLoader().getResourceAsStream("amazoneResponse.xml")), "utf-8");
	NodeList productNodes=XPathUtil.getNodeListtByXPath(productsInfo, "//product");
	Node productNode=null;
	String itemId=null;
	String price=null;
	String temp=null;
	for(int i=0;i<productNodes.getLength();i++){
		productNode=productNodes.item(i);
		temp=XPathUtil.getValueOfNode(productNode, "product_url");
		itemId=PatternUtils.getStrByRegex(temp, "item/(.*)");
		//默认取北京地区的价格
		price=XPathUtil.getValueOfNode(productNode, "sale_price");
		price=PatternUtils.getStrByRegex(price, "\n(.*?)\n");
		System.out.print(itemId+":"+price+"\n");

		if(CommonUtil.isEmptyOrNull(itemId)||CommonUtil.isEmptyOrNull(price)){
			continue;
		}
		
	}
	
}
}
